<?php


namespace app\controller\admin;


use app\common\service\redis\PoolRedis;
use app\model\AdminParents;
use app\model\AdminParentsData;
use app\model\AdminSchool;
use app\model\AdminStaff;
use app\model\AdminStaffData;
use app\model\AdminStudentParents;
use app\util\ReturnCode;
use think\facade\Request;
use think\facade\Validate;
use think\model\Relation;
use think\Response;

class Parents extends Base
{
    public function index(): Response {
        $limit = $this->request->get('size', config('apiadmin.ADMIN_LIST_DEFAULT'));
        $start = $this->request->get('page', 1);
        $school_id = $this->request->get('school_id', $this->userInfo['school_id']);
        $parent_name = $this->request->get('parent_name', '');
        $student_name = $this->request->get('student_name', '');
        $parent_phone = $this->request->get('parent_phone', '');
        $student_phone = $this->request->get('student_phone', '');

        $obj = (new AdminParents())->alias('AdminParents')
            ->where('AdminParents.is_delete', 0);
        if ($parent_phone) {
            $obj->where('AdminParents.phone', '=', $parent_phone);
        }
        if ($parent_name) {
            $obj->where('AdminParents.name', '=', "%{$parent_name}%");
        }

        $staff_where = [
            "is_delete" => 0,
            "status" => AdminStaff::AUDIT_PASS
        ];
        if ($school_id > 0) {
            array_push($staff_where, ['school_id', '=', $school_id]);
        }
        if ($student_name) {
            array_push($staff_where, ['name', '=', "%{$student_name}%"]);
        }
        if ($student_phone) {
            array_push($staff_where, ['phone', '=', $student_phone]);
        }

        $listObj = $obj
            ->with(['student' => function($query) use ($staff_where) {
                $query->with(['staff','school'])->where('is_delete',0)->order('create_time', 'desc'); //->hasWhere('staff', $staff_where)
            }])
            ->order('AdminParents.create_time', 'DESC')
            ->paginate(['page' => $start, 'list_rows' => $limit])->toArray();
        return $this->buildSuccess([
            'list'  => $listObj['data'],
            'count' => $listObj['total']
        ]);
    }

    public function edit(): Response {
        $data = Request::only(['id','name','sex','phone'], 'post');
        $validate = Validate::rule([
            'id|家长ID'=>'require',
            'name|姓名'=>'require',
            'sex|性别'=>'require',
            'phone|手机号' => 'require|mobile',
        ]);
        if (!$validate->check($data)) {
            return $this->buildFailed(ReturnCode::PARAM_INVALID, $validate->getError());
        }
        $parents = AdminParents::find($data['id']);
        if (!$parents) {
            return $this->buildFailed(ReturnCode::RECORD_NOT_FOUND, '记录未找到');
        }
        unset($data['id']);
        $parents->save($data);
        return $this->buildSuccess();
    }

    public function unbind(): Response {
        $sub = AdminStudentParents::find(input('get.id'));
        if (!$sub) {
            return $this->buildFailed(ReturnCode::RECORD_NOT_FOUND, '记录未找到');
        }
        $sub->is_delete = 1;
        $sub->delete_time = time();
        $sub->save();
        return $this->buildSuccess();
    }

    public function del(): Response {
        $parents = AdminParents::find(input('get.id'));
        if (!$parents) {
            return $this->buildFailed(ReturnCode::RECORD_NOT_FOUND, '记录未找到');
        }
        $parents->is_delete = 1;
        $parents->save();
        return $this->buildSuccess();
    }

    // 审核列表
    public function auditList(): Response {
        $limit = $this->request->get('size', config('apiadmin.ADMIN_LIST_DEFAULT'));
        $start = $this->request->get('page', 1);
        $school_id = $this->request->get('school_id', $this->userInfo['school_id']);
        $parent_name = $this->request->get('parent_name', '');
        $student_name = $this->request->get('student_name', '');
        $parent_phone = $this->request->get('parent_phone', '');
        $student_phone = $this->request->get('student_phone', '');

        $parent_where = [
            "is_delete" => 0
        ];
        if ($parent_name) {
             array_push($parent_where, ['name', 'like', "%{$parent_name}%"]);
        }
        if ($parent_phone) {
             array_push($parent_where, ['phone', '=', $parent_phone]);
        }
        $staff_where = [
            "is_delete" => 0
        ];
        if ($student_name) {
            array_push($staff_where, ['name', '=', "%{$student_name}%"]);
        }
        if ($student_phone) {
            array_push($staff_where, ['phone', '=', $student_phone]);
        }
        $where = [
            "AdminStudentParents.is_delete" => 0
        ];
        if ($school_id > 0) {
            array_push($where, ['AdminStudentParents.school_id', '=', $school_id]);
        }
        $listObj = AdminStudentParents::where($where)
            ->hasWhere('parent', $parent_where)
            ->hasWhere('staff', $staff_where)
            ->with(['parent', 'staff', 'school'])
            ->order('AdminStudentParents.create_time', 'DESC')
            ->paginate(['page' => $start, 'list_rows' => $limit])->toArray();
        return $this->buildSuccess([
            'list'  => $listObj['data'],
            'count' => $listObj['total']
        ]);
    }

    public function audit(): Response {
        $data = Request::only(['id','status','remark'], 'post');
        $validate = Validate::rule([
            'id|记录ID'=>'require',
            'status|审核状态'=>'require|in:1,2',
            'remark|拒绝理由'=>'requireIf:status,2',
        ]);
        if (!$validate->check($data)) {
            return $this->buildFailed(ReturnCode::PARAM_INVALID, $validate->getError());
        }
        $sub = AdminStudentParents::find($data['id']);
        if (!$sub) {
            return $this->buildFailed(ReturnCode::RECORD_NOT_FOUND, '记录未找到');
        }
        unset($data['id']);
        $data['audit_time'] = time();
        $sub->save($data);

        return $this->buildSuccess();
    }

    // 手机设备绑定列表
    public function deviceBindList(): Response {
        $limit = $this->request->get('size', config('apiadmin.ADMIN_LIST_DEFAULT'));
        $start = $this->request->get('page', 1);
        $school_id = $this->request->get('school_id', $this->userInfo['school_id']);
        $school_name = $this->request->get('school_name', '');
        $name = $this->request->get('name', '');
        $phone = $this->request->get('phone', '');
        $status = $this->request->get('status', null);

        $staffWhere = [
            ['is_delete', '=', 0]
        ];
        $obj = (new AdminParentsData());
        if ($school_id > 0) {
            array_push($staffWhere, ['school_id', '=', $school_id]);
        }
        if ($school_name) {
            $school_id_arr = AdminSchool::where('is_delete', 0)
                ->where('name','like', "%{$school_name}%")
                ->column('id');
            array_push($staffWhere, ['school_id', 'in', $school_id_arr]);
        }
        if ($name) {
            array_push($staffWhere, ['name', 'like', "%{$name}%"]);
        }
        if ($phone) {
            array_push($staffWhere, ['phone', '=', $phone]);
        }
        $where = [];
        if (!is_null($status)) {
            array_push($where, ['bind_device_status', '=', $status]);
        } else {
            array_push($where, ['bind_device_status', 'in', [1,2]]);
        }
        $list = $obj
            ->where($where)
            ->hasWhere('parents', $staffWhere)//->with(['parents', 'parents.school'])
            ->with(['parents'=>['school']])
            ->order(['last_bind_device_time' => 'DESC', 'last_login_time' => 'DESC'])
            ->paginate(['page' => $start, 'list_rows' => $limit])->toArray();
        return $this->buildSuccess([
            'list'  => $list['data'],
            'count' => $list['total']
        ]);
    }

    // 解绑设备
    public function deviceUnbind(): Response {
        $id = Request::param('id');
        $data = AdminParentsData::find($id);
        if (!$data) {
            return $this->buildFailed(ReturnCode::RECORD_NOT_FOUND, '记录未找到');
        }
        $data->bind_device_status = 3;
        $data->save();
        // 清除绑定设备记录
        $redis = PoolRedis::instance();
        $redis->delete('deviceUUID:parent'.$data->parent_id);
        return $this->buildSuccess();
    }
}